package mspbots.timedoctor.client.core.client;

import lombok.extern.log4j.Log4j2;
import mspbots.timedoctor.client.exception.BadRequestException;
import mspbots.timedoctor.client.oauth.V1AuthService;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * com.mspbots.sync.connectwis.TimeEntries
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/6/6
 */
@Log4j2
@Service
public class DoctorV1Client extends AbstractClient {

    public DoctorV1Client(WebClient.Builder builder, V1AuthService v1AuthService) {
        super(builder.baseUrl("https://webapi.timedoctor.com/")
                .defaultHeader("Accept", "application/json")
                .filter(ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
                    if (clientRequest.attribute("tenantId").isPresent()) {
                        Long tenantId = Long.parseLong(clientRequest.attribute("tenantId").get().toString());
                        return v1AuthService.getToken(tenantId)
                                .map(token -> ClientRequest.from(clientRequest)
                                        .headers(headers -> headers.setBearerAuth(token)).build());
                    } else {
                        return Mono.error(new BadRequestException(417, "Request-Processing authorization error no [tenantId]"));
                    }
                })).build());
    }
}
